#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    long long countSubarrays(vector<int>& nums, int minK, int maxK, int start = 0) {
        using LL = long long;
        int maxP = -1, minP = -1;
        LL res = 0;
        for (int i = start; i < nums.size(); i++)
        {
            if (nums[i] == maxK)
                maxP = i;
            if (nums[i] == minK)
                minP = i;
            if (nums[i] > maxK || nums[i] < minK)
                return res + countSubarrays(nums, minK, maxK, i + 1);
            int prev = min(minP, maxP);
            if (prev != -1)
                res += prev - start + 1;
        }
        return res;
    }
};